﻿namespace Shortcuts.Common
{
    using Microsoft.Phone.Shell;
    using Shortcuts.Globalization;
    using System;
    using System.Linq;

    public abstract class Tile
    {
        public abstract Settings Settings { get; }

        protected Tile()
        {
        }

        Uri uri;
        public Uri NavigationUri
        {
            get
            {
                if (uri == null)
                {
                    uri = new Uri(string.Format("/Views/NavigationPage.xaml?settings={0:G}", Settings), UriKind.Relative);
                }
                return uri;
            }
        }

        public void Pin()
        {
            var imageUri = new Uri(string.Format("/Assets/Tiles/{0:G}.png", Settings), UriKind.Relative);
            FlipTileData tile = new FlipTileData
            {
                Title = Settings.Localized(),
                BackgroundImage = imageUri,
                SmallBackgroundImage = imageUri
            };

            var oldTile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri == NavigationUri);
            if (oldTile != null)
            {
                oldTile.Update(tile);
            }
            else
            {
                ShellTile.Create(uri, tile, false);
            }
        }

        public void Delete()
        {
            var oldTile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri == NavigationUri);
            if (oldTile != null)
            {
                oldTile.Delete();
            }
        }

        public void Launch()
        {
            Windows.System.Launcher.LaunchUriAsync(new Uri(this.Settings.ToSettingsUrl(), UriKind.Absolute));
        }
    }
}
